'use strict';
/**
 * @fileoverview 远征
 * @author agl
 */

var _ = require('lodash');
var moment = require('moment');
var mongoose = require('mongoose');
var dataApi = require('../libs/dataApi');
var configUtil = require('../util/configUtil');
var constantUtil = require('../util/constantUtil');
var mgrUtil = require('../util/mgrUtil');
var eventType = require('../consts/eventType.js');
var soldierHpItemSchema = require('./expedition/soldierHpItemSchema.js');
var rivalItemSchema = require('./expedition/rivalItemSchema.js');
var expeditionShopItemSchema = require('./expedition/expeditionShopItemSchema.js');
var expeditionConf = require('../config/expeditionConf.js');

/**
 * 远征
 */
var expeditionSchema = new mongoose.Schema({
    // 角色id
    role_id: {
        type: Number,
        required: true,
        unique: true,
        index: true
    },

    // 远征币
    expedition_coin: {
        type: Number,
        default: 0
    },

    // 剩余次数
    remain_times: {
        type: Number,
        default: 1
    },

    // 通关关卡
    pass_id: {
        type: Number,
        default: 0
    },

    // 待开宝箱
    box_id: {
        type: Number,
        default: 0
    },

    // 出战阵容
    soldier_list: {
        type: [Number],
        default: []
    },

    // 士兵血量信息
    soldier_hp_list: {
        type: [soldierHpItemSchema],
        default: []
    },

    // 对手列表
    rival_list: {
        type: [rivalItemSchema],
        default: []
    },

    // 战斗时间
    battle_tm: {
        type: Number,
        default: 0
    },

    // 下次可挑战时间
    next_fight_tm: {
        type: Number,
        default: 0
    },

    // 商城物品
    expedition_shop: {
        type: [expeditionShopItemSchema],
        default: []
    },

    // 刷新商城次数
    refresh_shop_times: {
        type: Number,
        default: 0
    },
});

expeditionSchema.pre('save', function (next) {
    this.increment();
    if (!this.isNew && !!this.isModified()) {
        this.pushModify();
    }
    next();
});

/**
 * 获取修改
 * @return {[type]} [description]
 */
expeditionSchema.methods.getLastChange = function () {
    var change_info = this.toJSON();
    change_info.open_game_time = configUtil.getOpenGameTime();
    change_info.open_game_date = configUtil.getOpenGameDate();
    return change_info;
};

/**
 * 推送给用户
 * @return {[type]} [description]
 */
expeditionSchema.methods.push = function () {
    this.pushModify();
};

expeditionSchema.methods.pushModify = function () {
    var self = this;
    mgrUtil.sendStatusMessage(
        [self.role_id],
        eventType.ON_EXPEDITION_CHANGE,
        self.getLastChange(),
        function (err, fails) {
            if (err) {
                console.error('send expedition message error: %j, fail ids: %j', err, fails);
                return;
            }
        }
    );
};

if (!expeditionSchema.options.toJSON) {
    expeditionSchema.options.toJSON = {};
}
/* jshint unused:false */
expeditionSchema.options.toJSON.transform = function (doc, ret) {
    delete ret._id;
    delete ret.__v;
};

/**
 * 设置对手列表
 * @return {[type]} [description]
 */
expeditionSchema.methods.setRivalList = function (rival_list) {
    var self = this;
    self.rival_list = [];
    _.forEach(rival_list, function (rival) {
        self.rival_list.push(rival);
    });
};

/**
 * 设置远征阵容(只是保存，不检测士兵类型是否有效)
 * @return {[type]} [description]
 */
expeditionSchema.methods.setSoldierList = function (soldier_list) {
    var self = this;
    self.soldier_list = [];
    soldier_list = _.slice(soldier_list, 0, 5);
    _.forEach(soldier_list, function (soldier_type) {
        self.soldier_list.push(soldier_type);
    });
};

/**
 * 获取士兵当前血量
 * @return {[type]} [description]
 */
expeditionSchema.methods.getSoldierCurrHp = function (soldier_type, new_max_hp) {
    var self = this;
    var soldier_hp_info = _.find(self.soldier_hp_list, {
        soldier_type: soldier_type
    });
    if (!!soldier_hp_info) {
        var curr_hp = soldier_hp_info.curr_hp;
        if (curr_hp === 0) {
            // 挂掉的兵不考虑升级效果
            return 0;
        }
        if (new_max_hp > soldier_hp_info.max_hp) {
            curr_hp += new_max_hp - soldier_hp_info.max_hp;
            soldier_hp_info.max_hp = new_max_hp;
            soldier_hp_info.curr_hp = curr_hp;
        }
        return curr_hp;
    } else {
        self.soldier_hp_list.push({
            soldier_type: soldier_type,
            max_hp: new_max_hp,
            curr_hp: new_max_hp
        });
        return new_max_hp;
    }
};

/**
 * 设置士兵当前血量
 * @return {[type]} [description]
 */
expeditionSchema.methods.setSoldierCurrHp = function (hp_info_list) {
    var self = this;

    var hp_info_map = {};
    _.forEach(hp_info_list, function (hp_info) {
        hp_info_map[hp_info.soldier_type] = {
            curr_hp: hp_info.curr_hp
        };
    });

    _.forEach(self.soldier_hp_list, function (item) {
        var soldier_type = item.soldier_type;
        var new_item = hp_info_map[soldier_type];
        if (!!new_item) {
            item.curr_hp = new_item.curr_hp;
        }
    });

    for (var i = 0; i < self.soldier_list.length; i++) {
        var soldier_type = self.soldier_list[i];
        var new_item = hp_info_map[soldier_type];
        if (!!new_item && new_item.curr_hp <= 0) {
            self.soldier_list[i] = 0;
            self.markModified('soldier_list');
        }
    }
};

/**
 * 设置对手士兵当前血量
 * @return {[type]} [description]
 */
expeditionSchema.methods.setRivalHp = function (rival_idx, hp_info_list) {
    var self = this;
    if (rival_idx < 0 || rival_idx >= self.rival_list.length) {
        return false;
    }

    var hp_info_map = {};
    _.forEach(hp_info_list, function (hp_info) {
        hp_info_map[hp_info.soldier_type] = {
            curr_hp: hp_info.curr_hp
        };
    });

    var rival_info = self.rival_list[rival_idx];
    var soldier_list = rival_info.soldier_list;

    _.forEach(soldier_list, function (item) {
        var soldier_type = item.soldier_type;
        var new_item = hp_info_map[soldier_type];
        if (!!new_item) {
            item.attr.curr_hp = Math.floor(new_item.curr_hp);
        }
    });

    return true;
};

/**
 * 增加远征币
 * @return {[type]} [description]
 */
expeditionSchema.methods.addExpeditionCoin = function (coin) {
    this.expedition_coin += +coin;
};

/**
 * 增加远征币
 * @return {[type]} [description]
 */
expeditionSchema.methods.decExpeditionCoin = function (coin) {
    coin = +coin;
    if (this.expedition_coin < coin) {
        return false;
    }

    this.expedition_coin -= coin;
    return true;
};

/**
 * 取出指店位置商城物品信息
 */
expeditionSchema.methods.getShopItem = function (shop_pos) {
    var self = this;
    return _.find(self.expedition_shop, {
        shop_pos: shop_pos
    });
};

/**
 * 减少远征商城物品可购买次数
 */
expeditionSchema.methods.decShopItemCount = function (shop_pos) {
    var self = this;
    var success = false;
    _.forEach(self.expedition_shop, function (shop_item) {
        if (shop_item.shop_pos === shop_pos) {
            if (shop_item.count > 0) {
                shop_item.count--;
                success = true;
            }
            return false;
        }
        return true;
    });
    return success;
};

/**
 * 手动刷新商城
 */
expeditionSchema.methods.manulRefreshShop = function () {
    var self = this;

    var monster_shop_refresh_times_limit = constantUtil.value('monster_shop_refresh_times_limit');
    if (self.refresh_shop_times >= monster_shop_refresh_times_limit) {
        return false;
    }

    self.refresh_shop_times++;
    self.refreshShop();
    return true;
};

/**
 * 商城刷新
 */
expeditionSchema.methods.refreshShop = function () {
    var self = this;

    // 执行刷新
    self.expedition_shop = [];
    var expedition_shop = self.expedition_shop;

    // 必出
    var must_appear_list = expeditionConf.getMustAppearList();
    _.forEach(must_appear_list, function (item) {
        expedition_shop.push({
            shop_pos: item.shop_pos,
            shop_id: item.shop_id,
            count: item.count
        });
    });

    // 随机
    var monster_shop_num = constantUtil.value('monster_shop_num');
    var total_prob = expeditionConf.getTotalProb();
    var shop_rate_info = expeditionConf.getShopRateInfo();
    for (var shop_pos = must_appear_list.length + 1; shop_pos <= monster_shop_num; shop_pos++) {
        var rand_val = _.random(0, total_prob - 1);
        var shop_item = _findShopItemByRateVal(rand_val, shop_rate_info);
        if (!!shop_item) {
            expedition_shop.push({
                shop_pos: shop_pos,
                shop_id: shop_item.shop_id,
                count: shop_item.count
            });
        }
    }

    return true;
};

/**
 * 按随机概率值，查找商城ID
 */
var _findShopItemByRateVal = function (rate_val, shop_rate_info) {
    var shop_item = _.find(shop_rate_info, function (rate_item) {
        return rate_item.sum_rate > rate_val;
    });
    return shop_item;
};

mongoose.model('Expedition', expeditionSchema);
